const state = () => ({
  cart: JSON.parse(uni.getStorageSync('cart') || '[]')
})
const mutations = {
  addToCart (state, data) {
    const findResults = state.cart.find(x => x.goods_id === data.goods_id)
    if(findResults) {
      findResults.goods_count ++
    }
    else {
      state.cart.push(data)
    }
    this.commit('cart/saveToSetStorage')
  },
  subCart (state, id) {
    // const findResults = state.cart.findIndex(x => x.goods_id === id)
    // if(findResults !== -1) {
    //   state.cart.splice(findResults,1)
    // }
    state.cart = state.cart.filter(x => x.goods_id !== id)
    this.commit('cart/saveToSetStorage')
  },
   saveToSetStorage (state) {
     uni.setStorageSync('cart', JSON.stringify(state.cart))
   },
   updataGoodsState(state, obj) {
     const findResults = state.cart.find(x => x.goods_id === obj.goods_id)
     if(findResults) {
       findResults.goods_state = obj.goods_state
     }
     this.commit('cart/saveToSetStorage')
   },
   updataGoodsCount(state, obj) {
     const findResults = state.cart.find(x => x.goods_id === obj.goods_id)
     if(findResults) {
       findResults.goods_count = obj.goods_count
     }
     this.commit('cart/saveToSetStorage')
   },
   updataAllState (state, bool) {
      state.cart.forEach( x => x.goods_state = bool)
     this.commit('cart/saveToSetStorage')
   }
}
const actions = {}
const getters = {
  // 商品的总数量
  total (state) {
    // let c = 0
    // state.cart.forEach(x => c += x.goods_count)
    // return c
    return state.cart.reduce((total, item) => total += item.goods_count, 0)
  },
  // 已选中的商品总数量
  checkedCount (state) {
    return state.cart.filter(x=> x.goods_state ).reduce((total, item) => total += item.goods_count , 0)
  },
  // 已选中商品的总价格
  checkedMany (state) {
    return state.cart.filter(x=> x.goods_state ).reduce((total, item) => total += item.goods_count * item.goods_price , 0).toFixed(2)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}